import React, { PureComponent } from 'react';
import {
  Tag,
  Form,
  Select,
  Card,
  Input,
  Button,
  DatePicker,
  Table,
  Icon,
  Divider,
  message,
  Pagination,
} from 'antd';
import moment from 'moment';
import { connect } from 'dva';
import router from 'umi/router';
import styles from './Repair.less';
import AssessAddForm from './components/Assessment/AssessAddForm';
import { getAuthority } from '@/utils/authority';
import RenderAuthorized from '@/components/Authorized';
import AssessmentStyles from './Assessment.less';
const Authorized = RenderAuthorized(getAuthority());
// import AssessChildList from './components/Assessment/AssessChildList';
const FormItem = Form.Item;
const Option = Select.Option;
const currentYear = new Date().getFullYear();
const years = [
  { nodeName: currentYear, key: currentYear },
  { nodeName: currentYear - 1, key: currentYear - 1 },
  { nodeName: currentYear - 2, key: currentYear - 2 },
  { nodeName: currentYear - 3, key: currentYear - 3 },
];
@Form.create()
@connect(({ assessment, loading, global }) => ({
  currentUrl: global.currentUrl,
  elementAuth: global.elementAuth,
  companyList: assessment.companyList,
  AssessmentNodeList: assessment.AssessmentNodeList,
  AssessList: assessment.AssessList,
  PaginationChangeData: assessment.PaginationChangeData,
  loading: loading.effects['assessment/fetchAssessList'],
}))
class Assessment extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      pageindex: props.PaginationChangeData ? props.PaginationChangeData.pageindex : 1,
    };

    this.dispatch = this.props.dispatch;
  }
  returnColumn = () => {
    return [
      {
        title: '序号',
        dataIndex: 'index',
        render: (text, record, index) => `${index + 1}`,
        width: 50,
      },
      {
        title: '年份',
        width: 100,
        dataIndex: 'nf',
      },
      {
        title: '季度',
        width: 200,
        dataIndex: 'jd',
        render: (text, record) => <span>第{text}季度</span>,
      },
      {
        title: '月份',
        width: 200,
        dataIndex: 'yf',
        render: (text, record) => {
          if (text) return <span>{text}月</span>;
          else return <Tag color={'geekblue'}>{'平均得分'}</Tag>;
        },
      },
      {
        title: '养护单位',

        dataIndex: 'khbmmc',
      },
      {
        title: '考核分类',

        dataIndex: 'khlxmc',
      },
      {
        title: '考核评价总得分',
        width: 200,
        dataIndex: 'zbzdf',
        render: (text, record) => {
          if (!record.yf) return <Tag color={'geekblue'}>{text}</Tag>;
          else return <span>{text}</span>;
        },
      },

      {
        title: '操作',
        key: 'action',
        width: 220,
        render: (text, record) => {
          if (record.yf)
            return (
              <>
                <a
                  href="javascrips:;"
                  onClick={() => {
                    if (record.khlx == 1)
                      router.push({
                        pathname: `/municipal/assessment/assessDesForPip/${record.khbm}/${
                          record.nf
                        }/${record.yf}/${record.khlx}`,
                      });
                    else
                      router.push({
                        pathname: `/municipal/assessment/assessDesForRoad/${record.khbm}/${
                          record.nf
                        }/${record.yf}/${record.khlx}`,
                      });
                  }}
                >
                  <Icon type="profile" />
                  &nbsp; 查看汇总
                </a>
                <Divider type="vertical" />
                <a
                  href="javascrips:;"
                  onClick={() => {
                    router.push({
                      pathname: `/municipal/assessment/assessCheckedList/${record.khbm}/${
                        record.nf
                      }/${record.yf}/${record.khlx}`,
                    });
                    // this["EditForm"].fetchGetChechedkCompanyChildren({company:record.khbm,year:record.nf,month:record.yf,type:record.khlx});
                    // this["EditForm"].setState({visible:true});
                  }}
                >
                  <Icon type="schedule" />
                  &nbsp; 查看考核评价
                </a>
              </>
            );
        },
      },
    ];
  };
  queryList = () => {
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.setState({ pageindex: 1 });
        this.fetchAssessList({
          company: values.khbm,
          year: values.queryYear,
          month: values.queryQuarter,
          type: values.queryNode,
        });
      }
    });
  };
  resetData = () => {
    this.props.form.resetFields();
    this.queryList();
  };
  OnRef = (ref, payload) => {
    this[payload.type] = ref;
  };
  fetchGetCompany = () => {
    this.dispatch({
      type: 'assessment/fetchGetCompany',
      payload: {
        type: '养护维修',
      },
      callback: response => {
        message.error.error('养护单位获取失败');
        console.log(response);
      },
    });
  };
  fetchGetTemplate = ({ type = null } = {}) => {
    this.dispatch({
      type: 'assessment/fetchGetTemplate',
      payload: {
        type: type,
        year: new Date().getFullYear(),
      },
      callback: response => {
        message.error.error('考核模版获取失败');
        console.log(response);
      },
    });
  };
  fetchAssessList = ({
    pagesize = 10,
    pageindex = 1,
    company = null,
    year = currentYear,
    month = null,
    type = null,
  } = {}) => {
    console.log(year);
    this.dispatch({
      type: 'assessment/fetchAssessList',
      payload: {
        pagesize: pagesize,
        pageindex: pageindex,
        company: company,
        year: year,
        month: month,
        type: type,
      },
      callback: response => {
        message.error.error('列表获取失败');
        console.log(response);
      },
    });
  };
  onPaginationChange = page => {
    const values = this.props.form.getFieldsValue();
    this.setState({ pageindex: page });
    this.fetchAssessList({
      pageindex: page,
      company: values.khbm,
      year: values.queryYear,
      month: values.queryQuarter,
      type: values.queryNode,
    });
  };
  componentDidMount() {
    if (!this.props.companyList) this.fetchGetCompany();
    if (this.props.PaginationChangeData) {
      const values = this.props.PaginationChangeData.values;
      this.fetchAssessList({
        pageindex: this.state.pageindex,
        company: values.khbm.value,
        year: values.queryYear.value,
        month: values.queryQuarter.value,
        type: values.queryNode.value,
      });
      this.props.form.setFields(this.props.PaginationChangeData.values);
    } else {
      this.fetchAssessList();
      this.props.form.setFields(null);
    }

    this.fetchGetTemplate({ type: 1 });
    this.fetchGetTemplate({ type: 2 });
    this.getAuth();
  }
  getAuth = () => {
    const { dispatch, currentUrl, match } = this.props;
    dispatch({
      type: 'global/fetchUrl',
      payload: match.url,
      callback: response => {},
    });
    dispatch({
      type: 'global/fetchAuthorityElements',
      payload: { url: match.url },
    });
  };
  componentWillUnmount() {
    const values = this.props.form.getFieldsValue();
    this.dispatch({
      type: 'assessment/PaginationChangeData',
      payload: {
        values: {
          queryNode: { value: values.queryNode, errors: null },
          khbm: { value: values.khbm, errors: null },
          queryYear: { value: values.queryYear, errors: null },
          queryQuarter: { value: values.queryQuarter, errors: null },
        },
        pageindex: this.state.pageindex,
      },
    });
  }
  render() {
    const quarters = [
      { nodeName: '1月', key: '1' },
      { nodeName: '2月', key: '2' },
      { nodeName: '3月', key: '3' },
      { nodeName: '4月', key: '4' },
      { nodeName: '5月', key: '5' },
      { nodeName: '6月', key: '6' },
      { nodeName: '7月', key: '7' },
      { nodeName: '8月', key: '8' },
      { nodeName: '9月', key: '9' },
      { nodeName: '10月', key: '10' },
      { nodeName: '11月', key: '11' },
      { nodeName: '12月', key: '12' },
    ];
    const { getFieldDecorator } = this.props.form;
    const {
      elementAuth,
      companyList,
      AssessmentNodeList,
      AssessList,
      loading,
      PaginationChangeData,
    } = this.props;
    const pagination = {
      // size:'large',
      total: AssessList.total,
      onChange: this.onPaginationChange,
      current: this.state.pageindex,
      showTotal: (total, range) => `第${range[0]}条至${range[1]}条 | 总计${total}条记录数据 `,
    };
    return (
      <>
        <Card style={{ margin: '10px' }}>
          <Form layout="inline">
            <Authorized authority={elementAuth['selectOrg']}>
              <FormItem label="养护单位">
                {getFieldDecorator('khbm', { initialValue: null })(
                  <Select style={{ width: 120 }} style={{ width: '200px' }}>
                    {companyList &&
                      companyList.map(item => (
                        <Option key={item.Id} value={item.Id}>
                          {item.Name}
                        </Option>
                      ))}
                  </Select>
                )}
              </FormItem>
            </Authorized>
            <FormItem label="考核分类">
              {getFieldDecorator('queryNode', { initialValue: null })(
                <Select style={{ width: 120 }} style={{ width: '200px' }}>
                  {AssessmentNodeList.length > 0
                    ? AssessmentNodeList.map(item => (
                        <Option key={item.key} value={item.key}>
                          {item.nodeName}
                        </Option>
                      ))
                    : null}
                </Select>
              )}
            </FormItem>
            <FormItem label="年份">
              {getFieldDecorator('queryYear', { initialValue: currentYear })(
                <Select style={{ width: 120 }} style={{ width: '200px' }}>
                  {years.length > 0
                    ? years.map(item => (
                        <Option key={item.key} value={item.key}>
                          {item.nodeName}
                        </Option>
                      ))
                    : null}
                </Select>
              )}
            </FormItem>
            <FormItem label="月份">
              {getFieldDecorator('queryQuarter', { initialValue: null })(
                <Select style={{ width: 120 }} style={{ width: '200px' }}>
                  {quarters.length > 0
                    ? quarters.map(item => (
                        <Option key={item.key} value={item.key}>
                          {item.nodeName}
                        </Option>
                      ))
                    : null}
                </Select>
              )}
            </FormItem>
            <FormItem>
              <Button type="primary" onClick={this.queryList}>
                查询
              </Button>
            </FormItem>
            <FormItem>
              <Button onClick={this.resetData}>重置</Button>
            </FormItem>
            <Authorized authority={elementAuth['add']}>
              <FormItem>
                <Button
                  type="primary"
                  onClick={() => {
                    this['AddForm'].setState({ visible: true });
                  }}
                >
                  新增
                </Button>
              </FormItem>
            </Authorized>
          </Form>
        </Card>
        <Card
          title={
            <span style={{ borderLeft: '4px solid #3CB371', paddingLeft: '10px' }}>
              养护单位清单
            </span>
          }
          style={{ margin: '10px' }}
        >
          <Table
            className={styles.RepairTable}
            size="small"
            align={'center'}
            bordered
            loading={loading}
            dataSource={AssessList.data}
            columns={this.returnColumn()}
            pagination={pagination}
            rowClassName={(record, index) =>
              record.yf == null ? AssessmentStyles.antTableRow : ''
            }
          />
          <AssessAddForm
            OnRef={this.OnRef}
            fetchAssessList={this.fetchAssessList}
            resetData={this.resetData}
          />
        </Card>
      </>
    );
  }
}

export default Assessment;
